{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Reformer: Machine Translation",
      "provenance": [],
      "collapsed_sections": [
        "udDs_biH0n5U"
      ]
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "TPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "udDs_biH0n5U",
        "colab_type": "text"
      },
      "source": [
        "#### Copyright 2020 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "WPY-OyyM0pSs",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Licensed under the Apache License, Version 2.0 (the \"License\")\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "\n",
        " https://www.apache.org/licenses/LICENSE-2.0\n",
        "\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "psnUF-8c02o_",
        "colab_type": "text"
      },
      "source": [
        "# Reformer: Machine Translation [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google/trax/blob/master/trax/models/reformer/machine_translation.ipynb)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1lnRd_IoERdk",
        "colab_type": "text"
      },
      "source": [
        "This notebook was designed to run on TPU.\n",
        "\n",
        "To use TPUs in Colab, click \"Runtime\" on the main menu bar and select Change runtime type. Set \"TPU\" as the hardware accelerator."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8PluCmWbZIpJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Install JAX.\n",
        "!gsutil cp gs://trax-ml/reformer/jaxlib-0.1.39-cp36-none-manylinux2010_x86_64.whl .\n",
        "!gsutil cp gs://trax-ml/reformer/jax-0.1.59-cp36-none-manylinux2010_x86_64.whl .\n",
        "!pip install --upgrade -q ./jaxlib-0.1.39-cp36-none-manylinux2010_x86_64.whl\n",
        "!pip install --upgrade -q ./jax-0.1.59-cp36-none-manylinux2010_x86_64.whl\n",
        "\n",
        "# Make sure the Colab Runtime is set to Accelerator: TPU.\n",
        "import requests\n",
        "import os\n",
        "if 'TPU_DRIVER_MODE' not in globals():\n",
        "  url = 'http://' + os.environ['COLAB_TPU_ADDR'].split(':')[0] + ':8475/requestversion/tpu_driver0.1-dev20191206'\n",
        "  resp = requests.post(url)\n",
        "  TPU_DRIVER_MODE = 1\n",
        "\n",
        "# The following is required to use TPU Driver as JAX's backend.\n",
        "from jax.config import config\n",
        "config.FLAGS.jax_xla_backend = \"tpu_driver\"\n",
        "config.FLAGS.jax_backend_target = \"grpc://\" + os.environ['COLAB_TPU_ADDR']\n",
        "print(config.FLAGS.jax_backend_target)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yiPdBenoZwH6",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "!pip install --upgrade -q gin git+https://github.com/google/trax.git@v1.2.3\n",
        "\n",
        "from tensorflow.compat.v1.io.gfile import GFile\n",
        "import gin\n",
        "import os\n",
        "import pickle\n",
        "import jax\n",
        "import trax\n",
        "from trax.models.beam_search import Search\n",
        "from trax.supervised import inputs\n",
        "\n",
        "from tensor2tensor.data_generators.text_encoder import SubwordTextEncoder\n",
        "\n",
        "import numpy as np\n",
        "import jax.numpy as jnp\n",
        "\n",
        "from scipy.special import softmax"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "uCX88z9iXB7s",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Install sacreBLEU\n",
        "!pip install sacrebleu\n",
        "import sacrebleu"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "FQ89jHCYfhpg"
      },
      "source": [
        "## Load WMT14 data"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8S3h28Q9b_9B",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Download the newstest2014 English-to-German translation pairs\n",
        "!sacrebleu -t wmt14/full -l en-de --echo src > wmt14-en-de.src\n",
        "!sacrebleu -t wmt14/full -l en-de --echo ref > wmt14-en-de.ref"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "CBv2SDnWZEI7",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Load the source text and reference translations into Python\n",
        "refs = []\n",
        "for lineno, line in enumerate(sacrebleu.smart_open('wmt14-en-de.ref'), 1):\n",
        "  if line.endswith('\\n'):\n",
        "    line = line[:-1]\n",
        "  refs.append(line)\n",
        "srcs = []\n",
        "for lineno, line in enumerate(sacrebleu.smart_open('wmt14-en-de.src'), 1):\n",
        "  if line.endswith('\\n'):\n",
        "    line = line[:-1]\n",
        "  srcs.append(line)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "CbYw4eMXZGKa",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Set up our sub-word tokenizer\n",
        "tokenizer = SubwordTextEncoder(\n",
        "    'gs://trax-ml/reformer/mt/vocab.translate_ende_wmt32k.32768.subwords')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2NbOslppZGZ0",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Encode source sentences using the tokenizer\n",
        "input_ids = np.zeros((len(srcs), 128), dtype=jnp.int64)\n",
        "for i, x in enumerate(srcs):\n",
        "  x = tokenizer.encode(x)\n",
        "  assert len(x) <= 127\n",
        "  input_ids[i, :len(x)] = x\n",
        "  input_ids[i, len(x)] = 1"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YwzU64GmZTb2",
        "colab_type": "text"
      },
      "source": [
        "## Load the pre-trained model"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "VXjtCPxl3I82",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# We'll be using a pre-trained reversible transformer-base model.\n",
        "# First, load the config (which sets all needed hyperparameters).\n",
        "!gsutil cp gs://trax-ml/reformer/mt/config.gin ./config.gin\n",
        "gin.parse_config_file('./config.gin')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "IediBe8MXyLf",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Now we load the pre-trained model weights.\n",
        "with GFile('gs://trax-ml/reformer/mt/model.pkl', 'rb') as f:\n",
        "  model_weights = pickle.load(f)['weights']"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zY3hpgnI5Rgn",
        "colab_type": "text"
      },
      "source": [
        "## Beam search decoding"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "fc_VlhrBYW0u",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Set up beam search.\n",
        "beam_decoder = Search(\n",
        "    trax.models.Reformer, model_weights,\n",
        "    beam_size=4,\n",
        "    alpha=0.6,  # For length normalization, set to 0.6 following Vaswani et al.\n",
        "    eos_id=1,  # The stop token has id 1 in the vocabulary we use.\n",
        "    max_decode_len=146,\n",
        "    )"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bynTpreMYXPs",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 71
        },
        "outputId": "cfd24e01-617b-4beb-a5f2-98a7ce2e1449"
      },
      "source": [
        "pred_ids = []\n",
        "preds = []\n",
        "BATCH_SIZE = 1024\n",
        "for start in range(0, input_ids.shape[0], BATCH_SIZE):\n",
        "  print(start, '/', input_ids.shape[0], flush=True)\n",
        "  batch = input_ids[start:start+BATCH_SIZE]\n",
        "  seqs, scores = beam_decoder.decode(batch, batch_size=BATCH_SIZE)\n",
        "  # Select highest scoring output.\n",
        "  batch_pred_ids = seqs[:, -1]\n",
        "  pred_ids.append(batch_pred_ids)\n",
        "  preds.extend([\n",
        "      tokenizer.decode(pred.tolist(), strip_extraneous=True)\n",
        "      for pred in batch_pred_ids\n",
        "  ])"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "0 / 3003\n",
            "1024 / 3003\n",
            "2048 / 3003\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "c5Gq4qF_YY2i",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "outputId": "37a5e24f-9264-4d7a-dd74-065758c9a7e4"
      },
      "source": [
        "bleu = sacrebleu.corpus_bleu(preds, [refs], lowercase=True, tokenize='intl')\n",
        "print(bleu)"
      ],
      "execution_count": 14,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "BLEU = 27.86 59.5/33.5/21.3/14.2 (BP = 1.000 ratio = 1.020 hyp_len = 65943 ref_len = 64676)\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "olF4PpORpCTK",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        ""
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}
